package com.jd.risk.bankorder.service.bankorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.jd.risk.bankorder.dao.bankorder.*;
import com.jd.risk.bankorder.entity.bankorder.*;
import com.jd.risk.bankorder.util.HbaseQueryUtil;
import com.jd.risk.bankorder.util.TeslaJsonUtils;
import com.wycds.datacenter.api.DataReadService;
import kafka.utils.Json;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.*;

/**
 * Created by songjunou on 2017/5/24.
 */

@Service
public class BankOrderReplyService {
    private static SerializeConfig mapping = new SerializeConfig();
    private static String dateFormat;
    static {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

    @Autowired
    private DataReadService dataReadService;

    @Autowired
    private TeslaOrderInfoMapper teslaOrderInfoMapper;

    @Autowired
    private TeslaBankRequestMapper teslaBankRequestMapper;

    @Autowired
    private TeslaReplyInfoMapper teslaReplyInfoMapper;

    @Autowired
    private TeslaConsigneeMapper teslaConsigneeMapper;

    @Autowired
    private TeslaPaymentInfoMapper teslaPaymentInfoMapper;

    @Autowired
    private BankOrderService bankOrderService;



    public List<TeslaOrderInfo> getOrderInfoByBankRequestNo(String bankRequestNo) {

        TeslaOrderInfoExample teslaOrderInfoExample = new TeslaOrderInfoExample();
        teslaOrderInfoExample.createCriteria().andBankRequestNoEqualTo(bankRequestNo);
        List<TeslaOrderInfo> infos = teslaOrderInfoMapper.selectByExample(teslaOrderInfoExample);

        return  infos;
    }

    public List<TeslaOrderInfo> getOrderInfoByRequestId(Long requestId) {

        TeslaOrderInfoExample teslaOrderInfoExample = new TeslaOrderInfoExample();
        teslaOrderInfoExample.createCriteria().andRequestIdEqualTo(requestId);
        List<TeslaOrderInfo> infos = teslaOrderInfoMapper.selectByExample(teslaOrderInfoExample);
        return  infos;
    }

    public List<TeslaOrderInfo> queryOrderInfoByBankNoHbase(String bankOrderNo ,Date tradeDate)
    {
        String tradeTT = DateFormatUtils.format(tradeDate , "yyyy-MM-dd");
        String startTime = tradeTT+" 00:00:00";
        String endTime = tradeTT+" 59:59:59";
        List<TeslaOrderInfo> infos = new ArrayList<TeslaOrderInfo>();
        Map<String,String> map = new HashMap<String, String>();
        map.put("bankOrderNo",bankOrderNo);
        map.put("tradeTypeCode","03");
        map.put("subTradeTypeCode","01");
        map.put("paymentCode","02");
        map.put("startTime",startTime);
        map.put("endTime" ,endTime);
        List<Map<String, String>> results =  HbaseQueryUtil.queryTradeInfo(map , dataReadService);
        for(Map<String, String>  item :results){
            TeslaOrderInfo teslaOrderInfo = new TeslaOrderInfo();
            teslaOrderInfo.setBankRequestNo(bankOrderNo);
            teslaOrderInfo.setTradeNo(item.get("trade_no"));
            teslaOrderInfo.setBankOrderNo(item.get("bank_order_no"));
            teslaOrderInfo.setMerchantNo(item.get("merchant_no"));
            teslaOrderInfo.setAddGoodsOrderNo(item.get("add_goods_order_no"));
            teslaOrderInfo.setMerchantTradeNo(item.get("merchant_trade_no"));
            teslaOrderInfo.setTradePayRequestNo(item.get("trade_pay_request_no"));
//            teslaOrderInfo.setMerchantName();
            infos.add(teslaOrderInfo);
        }
        return infos;
    }

    public List<TeslaOrderInfo> queryOrderInfoByCardpanHbase(String cardPan ,Date tradeDate){
        String tradeTT = DateFormatUtils.format(tradeDate , "yyyy-MM-dd");
        String startTime = tradeTT+" 00:00:00";
        String endTime = tradeTT+" 59:59:59";
        List<TeslaOrderInfo> infos = new ArrayList<TeslaOrderInfo>();
        Map<String,String> map = new HashMap<String, String>();
        map.put("tradeTypeCode","03");
        map.put("subTradeTypeCode","01");
        map.put("paymentCode","02");
        map.put("cardPan",cardPan);
        map.put("startTime",startTime);
        map.put("endTime" ,endTime);
        List<Map<String, String>> results =  HbaseQueryUtil.queryTradeInfo(map , dataReadService);
        for(Map<String, String>  item :results){
            TeslaOrderInfo teslaOrderInfo = new TeslaOrderInfo();
            teslaOrderInfo.setBankRequestNo(cardPan);
            teslaOrderInfo.setTradeNo(item.get("trade_no"));
            teslaOrderInfo.setBankOrderNo(item.get("bank_order_no"));
            teslaOrderInfo.setMerchantNo(item.get("merchant_no"));
            teslaOrderInfo.setAddGoodsOrderNo(item.get("add_goods_order_no"));
            teslaOrderInfo.setMerchantTradeNo(item.get("merchant_trade_no"));
            teslaOrderInfo.setTradePayRequestNo(item.get("trade_pay_request_no"));
//            teslaOrderInfo.setMerchantName();
            infos.add(teslaOrderInfo);
        }
        return infos;
    }

    /**
     *  保存回复信息
     * @param orderInfo
     * @param replyInfo
     * @param bankRequest
     * @return
     */
    public boolean saveOrSendReply(List<TeslaOrderInfo> orderInfo, TeslaReplyInfo replyInfo, TeslaBankRequest bankRequest) {

        for(TeslaOrderInfo tinfo :orderInfo){
            if(null == tinfo.getId()){
                tinfo.setCreatedDate(new Date());
                teslaOrderInfoMapper.insertSelective(tinfo);
            }else{
                teslaOrderInfoMapper.updateByPrimaryKeySelective(tinfo);
            }
        }
        if(null== replyInfo.getId())
        {
            replyInfo.setCreatedDate(new Date());
            teslaReplyInfoMapper.insertSelective(replyInfo);
        }else{
            teslaReplyInfoMapper.updateByPrimaryKeySelective(replyInfo);
        }
        if(null!=bankRequest){
            teslaBankRequestMapper.updateByPrimaryKeySelective(bankRequest);
        }
        TeslaConsigneeExample teslaConsigneeExample = new TeslaConsigneeExample();
        teslaConsigneeExample.createCriteria().andRequestIdEqualTo(bankRequest.getId());
        teslaConsigneeMapper.deleteByExample(teslaConsigneeExample);                //删除历史数据
        List<TeslaConsignee>  teslaConsignees = getConsigneesByInterface(orderInfo);
        for(TeslaConsignee consignee :teslaConsignees){                                 //保存订单信息
            consignee.setCreatedDate(new Date());
            consignee.setRequestId(bankRequest.getId());
            teslaConsigneeMapper.insertSelective(consignee);
        }
        TeslaPaymentInfoExample teslaPaymentInfoExample = new TeslaPaymentInfoExample();
        teslaPaymentInfoExample.createCriteria().andRequestIdEqualTo(bankRequest.getId());
        teslaPaymentInfoMapper.deleteByExample(teslaPaymentInfoExample);            // 删除历史数据
        List<TeslaPaymentInfo>  paymentInfos = getPaymentByInterface(bankRequest);
        for(TeslaPaymentInfo paymentInfo :paymentInfos){                                //保存赔付信息
            paymentInfo.setCreatedDate(new Date());
            paymentInfo.setRequestId(bankRequest.getId());
            teslaPaymentInfoMapper.insertSelective(paymentInfo);
        }
        return true;
    }

    /**
     *  从数据库中读取相关信息
     * @param map
     * @param requestId
     */
    public void getAllDetailForShow(ModelMap map, Long requestId) {
        List<TeslaBankRequest> requests = bankOrderService.queryByRequestId(requestId);
        TeslaBankRequest request = null;
        if(CollectionUtils.isNotEmpty(requests)) //获取请求信息
        {
            request = requests.get(0);
            map.put("request", TeslaJsonUtils.toJson(request));
            map.put("bankRequestType",requests.get(0).getBankRequestType());
        }
        String bankRequestNo = requests.get(0).getBankRequestNo();
        List<TeslaOrderInfo> orderInfos = getOrderInfoByRequestId(requestId);
        if(CollectionUtils.isNotEmpty(orderInfos))      //获取订单信息
        {
            map.put("order", TeslaJsonUtils.toJson(orderInfos));
        }else {
            if(request.getBankRequestType().equals("0")){
                orderInfos = queryOrderInfoByBankNoHbase(bankRequestNo, request.getTradeDate());
            }else{
                orderInfos = queryOrderInfoByCardpanHbase(bankRequestNo ,request.getTradeDate());
            }
            map.put("order" , TeslaJsonUtils.toJson(orderInfos));
        }

        TeslaReplyInfoExample teslaReplyInfoExample = new TeslaReplyInfoExample();
        teslaReplyInfoExample.createCriteria().andRequestIdEqualTo(requestId);
        List<TeslaReplyInfo> replyInfos =   teslaReplyInfoMapper.selectByExample(teslaReplyInfoExample);
        if(CollectionUtils.isNotEmpty(replyInfos))     //获取基本反馈信息
        {
            TeslaReplyInfo replyInfo = replyInfos.get(0);
            map.put("reply",TeslaJsonUtils.toJson(replyInfo));
        }

        TeslaConsigneeExample teslaConsigneeExample = new TeslaConsigneeExample();
        teslaConsigneeExample.createCriteria().andRequestIdEqualTo(requestId);
        List<TeslaConsignee> teslaConsignees = teslaConsigneeMapper.selectByExample(teslaConsigneeExample);
        if(CollectionUtils.isNotEmpty(teslaConsignees)){
            map.put("consignee", TeslaJsonUtils.toJson(teslaConsignees));
        }else{
            teslaConsignees = getConsigneesByInterface(orderInfos);
            map.put("consignee", TeslaJsonUtils.toJson(teslaConsignees));
        }
        TeslaPaymentInfoExample teslaPaymentInfoExample = new TeslaPaymentInfoExample();
        teslaConsigneeExample.createCriteria().andRequestIdEqualTo(requestId);
        List<TeslaPaymentInfo> paymentInfos = teslaPaymentInfoMapper.selectByExample(teslaPaymentInfoExample);
        if(CollectionUtils.isNotEmpty(paymentInfos)){
            map.put("payment",TeslaJsonUtils.toJson(paymentInfos));
        }else{
            paymentInfos = getPaymentByInterface(request);
            map.put("payment",TeslaJsonUtils.toJson(paymentInfos));
        }
    }

    /**
     * 获取收货地址
     * @param orderInfos
     * @return
     */
    private List<TeslaConsignee> getConsigneesByInterface(List<TeslaOrderInfo> orderInfos) {
        List<TeslaConsignee> teslaConsignees = new ArrayList<TeslaConsignee>();
        for(TeslaOrderInfo info :orderInfos){
            TeslaConsignee teslaConsignee  = new TeslaConsignee();
            teslaConsignee.setMerchantTradeNo(info.getMerchantTradeNo());
            teslaConsignee.setConsigneeIp("127.0.0.1");
            teslaConsignee.setConsigneeGoods("测试商品");
            teslaConsignee.setConsigneeAddress("测试地址");
            teslaConsignee.setConsigneeName("你好");
            teslaConsignee.setConsigneePhone("12122121");
            teslaConsignees.add(teslaConsignee);
        }
        return teslaConsignees;
    }


    public  List<TeslaPaymentInfo> getPaymentByInterface(TeslaBankRequest teslaBankRequest)
    {
            List<TeslaPaymentInfo> paymentInfos = new ArrayList<TeslaPaymentInfo>();
            TeslaPaymentInfo pinfo1 = new TeslaPaymentInfo();
            pinfo1.setPaymentState("1");
            pinfo1.setPaymentCardPan("123456");
            pinfo1.setPaymentAmount(100L);
            pinfo1.setPaymentTime(new Date());
            paymentInfos.add(pinfo1);
            TeslaPaymentInfo pinfo2 = new TeslaPaymentInfo();
            pinfo2.setPaymentState("1");
            pinfo2.setPaymentAmount(200L);
            pinfo2.setPaymentCardPan("123456");
            pinfo2.setPaymentTime(new Date());
            paymentInfos.add(pinfo2);
        return paymentInfos;
    }

}
